// const dispatch = obj => {
// 	const ev = document.createEvent('MouseEvents')
// 	ev.initMouseEvent(
// 		'click', 
// 		true, 
// 		false, 
// 		window, 
// 		0, 
// 		0, 
// 		0, 
// 		0, 
// 		0, 
// 		false, 
// 		false, 
// 		false, 
// 		false, 
// 		0, 
// 		null
// 	)
// 	obj.dispatchEvent(ev)
// }
import $time from './time'
const types = {
	xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet charset=utf-8',
	xls: 'application/vnd.ms-excel charset=utf-8',
	pdf: 'application/pdf charset=utf-8',
	docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document charset=utf-8',
	txt : 'application/text charset=utf-8',
	png : 'image/png',
	jpg : 'image/jpg',
	jpeg : 'image/jpeg',
	gif : 'image/gif',
	avi : 'video/x-msvide',
	mp4 : 'video/mp4'
}
// 将 base64 转为 Binary
const base64ToBinary = base64Data => {
	let binaryString = window.atob( base64Data )		 // window.atob()用于解码使用 base64 编码的字符串
	let binaryLen = binaryString.length
	let bytes = new Uint8Array(binaryLen)
	for (var i = 0; i < binaryLen; i++) {
		let ascii = binaryString.charCodeAt(i)		  // charCodeAt()用于返回指定位置处字符的Unicode编码
		bytes[i] = ascii
	}
	return bytes
}
const Index = {
	// blobDispath(data, option) {
	// 	const {fileType = 'xlsx', fileName = 'download'} = option ?? {}
		
	// 	const urlObject = window.URL || window.webkitURL || window
		
	// 	const blob = new Blob([ data ],  { type: types[ fileType ]})
		
	// 	const link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
		
	// 	link.href = urlObject.createObjectURL(blob)
		
	// 	link.download = fileName + '_' + $time.format(Date.now(), { t:'all' }) + '.' + fileType
		
	// 	link.style.display = 'none'
		
	// 	dispatch(link)
	// },
	blob(data, option){
		const {fileType = 'xlsx', fileName = 'download', type='base64'} = option ?? {}
		
		const urlObject = window.URL || window.webkitURL || window
		
		const blob = new Blob([ type === 'base64' ? base64ToBinary(data) : data ],  { type: types[ fileType ] })
		
		const a = document.createElement('a')
		
		a.href = urlObject.createObjectURL(blob)
		
		a.download = fileName + '_' + $time.format(Date.now(), { t:'all' }) + '.' + fileType
		
		a.style.display = 'none'
		
		document.body.appendChild( a )
		
		a.click()
		
		document.body.removeChild( a )
	},
	// url 后台下载
	form(url){
		const form = document.createElement('form')
		form.method = 'post'
		form.action = window.$config.api() + url
		form.target = '_blank'
		// token 验证
		const tokenInput = document.createElement('input')
		tokenInput.type = 'hidden'
		tokenInput.name ='token'
		tokenInput.value = window.$fn.getToken()
		//
		form.appendChild(tokenInput)
		document.body.appendChild(form)
		form.submit()
		document.body.removeChild(form)
	}
}

export default Index